'use client'

import React, { useState, useMemo, useCallback, memo } from 'react'
import { Card, Table, Button, Input, Select, Form, Modal, Space, message, Popconfirm } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'

interface Department {
  id: number
  name: string
  code: string
  parentId: number | null
  leader: string
  phone: string
  email: string
  status: string
  createTime: string
}

// 使用 memo 优化组件，避免不必要的重渲染
const DepartmentsPage = memo(function DepartmentsPage() {
  const [departments, setDepartments] = useState<Department[]>([
    { id: 1, name: '技术部', code: 'TECH', parentId: null, leader: '张三', phone: '13800138001', email: 'tech@example.com', status: '启用', createTime: '2024-01-15 10:00:00' },
    { id: 2, name: '人事部', code: 'HR', parentId: null, leader: '李四', phone: '13800138002', email: 'hr@example.com', status: '启用', createTime: '2024-01-15 10:00:00' },
    { id: 3, name: '财务部', code: 'FIN', parentId: null, leader: '王五', phone: '13800138003', email: 'finance@example.com', status: '启用', createTime: '2024-01-15 10:00:00' },
    { id: 4, name: '前端组', code: 'FE', parentId: 1, leader: '赵六', phone: '13800138004', email: 'fe@example.com', status: '启用', createTime: '2024-01-15 10:00:00' },
    { id: 5, name: '后端组', code: 'BE', parentId: 1, leader: '钱七', phone: '13800138005', email: 'be@example.com', status: '禁用', createTime: '2024-01-15 10:00:00' },
  ])
  const [filteredDepartments, setFilteredDepartments] = useState<Department[]>(departments)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editingDepartment, setEditingDepartment] = useState<Department | null>(null)
  const [searchForm] = Form.useForm()
  const [form] = Form.useForm()

  // 使用 useMemo 优化选项数据
  const statusOptions = useMemo(() => ['启用', '禁用'], [])

  // 使用 useMemo 优化列定义
  const columns = useMemo(() => [
    { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
    { title: '部门名称', dataIndex: 'name', key: 'name' },
    { title: '部门编码', dataIndex: 'code', key: 'code' },
    { 
      title: '上级部门', 
      dataIndex: 'parentId', 
      key: 'parentId',
      render: (parentId: number | null) => {
        if (!parentId) return '顶级部门'
        const parent = departments.find(d => d.id === parentId)
        return parent ? parent.name : '-'
      }
    },
    { title: '负责人', dataIndex: 'leader', key: 'leader' },
    { title: '联系电话', dataIndex: 'phone', key: 'phone' },
    { title: '邮箱', dataIndex: 'email', key: 'email' },
    { title: '状态', dataIndex: 'status', key: 'status' },
    { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_: any, record: Department) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除这个部门吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ], [departments])

  // 查询栏筛选逻辑 - 使用 useCallback 优化
  const handleSearch = useCallback((values: any) => {
    let data = [...departments]
    if (values.name) {
      data = data.filter(d => d.name.includes(values.name))
    }
    if (values.leader) {
      data = data.filter(d => d.leader.includes(values.leader))
    }
    if (values.status) {
      data = data.filter(d => d.status === values.status)
    }
    setFilteredDepartments(data)
  }, [departments])

  const handleReset = useCallback(() => {
    searchForm.resetFields()
    setFilteredDepartments(departments)
  }, [searchForm, departments])

  const handleAdd = useCallback(() => {
    setEditingDepartment(null)
    form.resetFields()
    setIsModalVisible(true)
  }, [form])

  const handleEdit = useCallback((department: Department) => {
    setEditingDepartment(department)
    form.setFieldsValue(department)
    setIsModalVisible(true)
  }, [form])

  const handleDelete = useCallback((id: number) => {
    // 删除部门及其子部门
    const deleteIds = new Set([id])
    const findChildren = (parentId: number) => {
      departments.forEach(dept => {
        if (dept.parentId === parentId) {
          deleteIds.add(dept.id)
          findChildren(dept.id)
        }
      })
    }
    findChildren(id)
    setDepartments(departments.filter(dept => !deleteIds.has(dept.id)))
    setFilteredDepartments(filteredDepartments.filter(dept => !deleteIds.has(dept.id)))
    message.success('删除成功')
  }, [departments, filteredDepartments])

  const handleModalOk = useCallback(() => {
    form.validateFields().then((values: any) => {
      if (editingDepartment) {
        setDepartments(departments.map(dept =>
          dept.id === editingDepartment.id ? { ...dept, ...values } : dept
        ))
        setFilteredDepartments(filteredDepartments.map(dept =>
          dept.id === editingDepartment.id ? { ...dept, ...values } : dept
        ))
        message.success('更新成功')
      } else {
        const newDepartment: Department = {
          id: Math.max(...departments.map(d => d.id)) + 1,
          ...values,
          createTime: new Date().toLocaleString()
        }
        setDepartments([...departments, newDepartment])
        setFilteredDepartments([...filteredDepartments, newDepartment])
        message.success('创建成功')
      }
      setIsModalVisible(false)
      form.resetFields()
    })
  }, [editingDepartment, departments, filteredDepartments, form])

  return (
    <div style={{ padding: 16, height: '100%', minHeight: 0, display: 'flex', flexDirection: 'column' }}>
      {/* 查询条件卡片 */}
      <Card style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
        >
          <Form.Item name="name" label="部门名称">
            <Input placeholder="请输入部门名称" allowClear style={{ width: 160 }} />
          </Form.Item>
          <Form.Item name="leader" label="负责人">
            <Input placeholder="请输入负责人" allowClear style={{ width: 140 }} />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="全部" allowClear style={{ width: 120 }}>
              {statusOptions.map(st => (
                <Select.Option key={st} value={st}>{st}</Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">查询</Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={handleReset}>重置</Button>
          </Form.Item>
        </Form>
      </Card>

      {/* 表格内容卡片 */}
      <Card 
        style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }} 
        styles={{ body: { padding: '12px 24px', flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' } }}
      >
        <div style={{ marginTop: 0, marginBottom: 8, display: 'flex', justifyContent: 'flex-end' }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增部门
          </Button>
        </div>
        <Table
          columns={columns}
          dataSource={filteredDepartments}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          }}
        />
      </Card>

      <Modal
        title={editingDepartment ? '编辑部门' : '新增部门'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="部门名称"
            rules={[{ required: true, message: '请输入部门名称' }]}
          >
            <Input placeholder="请输入部门名称" />
          </Form.Item>
          <Form.Item
            name="code"
            label="部门编码"
            rules={[{ required: true, message: '请输入部门编码' }]}
          >
            <Input placeholder="请输入部门编码，如：TECH" />
          </Form.Item>
          <Form.Item
            name="parentId"
            label="上级部门"
          >
            <Select placeholder="请选择上级部门" allowClear>
              <Select.Option value={null}>顶级部门</Select.Option>
              {departments.map(dept => (
                <Select.Option key={dept.id} value={dept.id}>
                  {dept.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="leader"
            label="负责人"
            rules={[{ required: true, message: '请输入负责人' }]}
          >
            <Input placeholder="请输入负责人姓名" />
          </Form.Item>
          <Form.Item
            name="phone"
            label="联系电话"
            rules={[{ required: true, message: '请输入联系电话' }]}
          >
            <Input placeholder="请输入联系电话" />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入正确的邮箱格式' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Select.Option value="启用">启用</Select.Option>
              <Select.Option value="禁用">禁用</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
})

export default DepartmentsPage 